<template>
  <div class="login">
    <div class="box">
      <h2>登录</h2>
      <el-form label-position="top" label-width="100px" :model="form" ref="ruleFormRef" style="max-width: 460px"
        :rules="rules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" clearable />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" show-password clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { userlogin } from "../request/api";
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";

const router = useRouter();
const store = useStore();
const ruleFormRef: any = ref<FormInstance>();
const rules = reactive<FormRules>({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    // { min: 3, max: 5, message: "Length should be 3 to 5", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    // { min: 3, max: 5, message: "Length should be 3 to 5", trigger: "blur" },
  ],
});
let form = reactive({
  username: "",
  password: "",
});

function submitForm() {
  ruleFormRef.value.validate((val: any) => {
    if (!val) {
      return;
    }
    userlogin(form).then((res: any) => {
      if (res.code == 200) {
        store.commit("changeUserInfo", res.list);
        sessionStorage.setItem("userInfo", JSON.stringify(res.list));
        ElMessage.success(res.msg);
        router.push("/home");
        return;
      }
      ElMessage.warning(res.msg);
    });
  });
}
</script>

<style scoped>
.login {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.box {
  width: 400px;
  text-align: center;
}

.el-button {
  width: 100%;
}
</style>